import sys
import time
import traceback

from lxml import etree
from selenium.webdriver import Keys
from dbse.mysql.db_mysql_insert import getDataBase
from sel.proxy.selenium_proxy_util import initSelWireChromePlus
from sel.proxy.selenium_proxy_util import tab2Page
from selenium.webdriver.common.action_chains import ActionChains
from dbse.mysql.db_entity_stock_ths_gn_current_info import StockCurrentThsGnInfo
from dbse.mysql.db_mysql_insert import addStockThsGnCurrentInfo
from date.dateUtil import getDateTime
from utils.DateUtil import isStockOpen, isOpenToday
import static.globals as sg

def handlePage(browser,db,gnCode):
    content = browser.page_source
    html = etree.fromstring(content,etree.HTMLParser())
    result = html.xpath('//div[@class="board-infos"]//dl//dd')
    main = html.xpath('//div[@class="board-hq"]')
    price_current = main[0].getchildren()[1].text
    gn_name= main[0].getchildren()[0].text
    add_sql = 'INSERT INTO stock_ths_gn_current_info (gn_code,gn_name,price_begin,price_yesterday,price_end,price_max,price_min,price_increase_rate,rank,up_num,down_num,fund_input,amount,trunover,sta_datetime,price_current) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
    # 保存数据
    entity = StockCurrentThsGnInfo(gnCode,
                                   gn_name,                                            #gn_name
                                   result[0].text,                                  #price_begin
                                   result[1].text,                                  #price_yesterday
                                   None,                                            #price_end
                                   result[3].text,                                  #price_max
                                   result[2].text,                                  #price_min
                                   None,                                            #price_increase_rate
                                   result[6].text.split("/")[0],                    #rank
                                   result[7].getchildren()[0].text,                 #up_num
                                   result[7].getchildren()[1].text,                 #down_num
                                   result[8].text,                                  #fund_input
                                   result[9].text,                                  #amount
                                   result[4].text,                                  #trunover
                                   getDateTime(),                                   #sta_datetime
                                   price_current                                    # price_current
                                   )
    addStockThsGnCurrentInfo(db,add_sql,entity)

def startWork(profile,batch):
    try:
        # 初始化chrome useTab 为True
        browser = initSelWireChromePlus(useProxy=False,isHeadless=False,host='https://q.10jqka.com.cn',useTab=True)
        time.sleep(1)
        offset = 7 * (int(batch) -1)
        query_sql = f'select distinct t1.gn_code ,t1.gn_name ,t1.gn_url from stock_ths_gn t1 join stock_ths_gn_current_config t2 on t1.gn_code = t2.gn_code where t2.type = 2 order by t1.gn_code desc limit 7 offset {offset}'
        db = getDataBase(profile)
        cursor = db.cursor()
        print(query_sql)
        cursor.execute(query_sql)
        gns = cursor.fetchall()
        gnNums = len(gns)
        #创建所有标签页
        for gn in gns:
            browser.execute_script("window.open('', '_blank');")

        #统计所有标签页
        handles = browser.window_handles

        #加载所有标签页
        for index, gn in enumerate(gns):
            url = gn[2]
            tab2Page(browser,handles,index+1,url)

        ## 只有在开盘的情况下运行
        while True:
            if(isStockOpen()):          # 开盘的情况下 才执行
                for index , gn in enumerate(gns):
                    time.sleep(15)
                    browser.switch_to.window(handles[index+1])
                    browser.execute_script("location.reload();")
                    # 处理数据
                    handlePage(browser,db,gn[0])
            else:
                time.sleep(30)

    except Exception as e:
        print(f"异常信息: {e}")
        print("详细堆栈信息:")
        traceback.print_exc()  # 打印完整的堆栈跟踪
        print(f"======================批次{batch}发生异常,等待重启======================")
        browser.quit()
        # 打印当前页面
        # print(browser.page_source)
        time.sleep(2)
        ## 重启任务
        startWork(profile,batch)

profile = sys.argv[1:][0]
batch = sys.argv[1:][1]
sg.batch = batch
sg.profile = profile
if isOpenToday():
    # print("==================Stock is  open today==================")
    startWork(profile,batch)

